const mongoose = require("mongoose");

async function main() {
  try {
    // 端口号，如果是默认的 27017 可以省略
    await mongoose.connect("mongodb://127.0.0.1/test");
    console.log("数据库连接成功");

    // 创建 schema
    const studentSchema = new mongoose.Schema({
      name: String,
      sex: Number, // 0 - 男 1 - 女
      age: {
        type: Number,
        default: 18,
      },
      address: String,
    });

    // 创建 Model
    const StudentModel = mongoose.model("Student", studentSchema);

    // 创建 实例 document
    const studentDoc = new StudentModel({
      name: "张三",
      sex: 0,
      address: "深圳市",
    });

    // 写入到数据库中
    await studentDoc.save();
    console.log("写入成功");
  } catch (error) {
    console.log("失败", error);
  }
}

main();
